package com.hzit.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hzit.common.constants.TokenConstants;
import com.hzit.common.entity.LoginUser;
import com.hzit.common.entity.User;
import com.hzit.common.util.JwtUtil;
import com.hzit.mapper.UserMapper;
import com.hzit.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hzit.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author wf
 * @since 2024-01-25
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

	@Autowired
	private StringRedisTemplate redisTemplate;

	//1. 用户登录处理
	@Override
	public Map<String, Object> login(UserVo vo) {
		//第一部分: 将登录用户信息放到redis中
		//1. 根据用户名查询用户
		LoginUser user = findByUserByUsername(vo.getUsername());
		//2. 如果存在用户名，就做如下两件事：
		//2.1 利用uuid生成token
		String token = UUID.randomUUID().toString().replace("-","");
		user.setToken(token);
		//2.2 根据用户名查询权限串
		List<String> permissions = baseMapper.findPermissionsByUsername(vo.getUsername());
		//2.3 为登录用户设置权限串
		user.setPermissions(permissions);
		//2.4  定义要存放到redis中的key
		String key = getKey(token);
		//2.5 向reids中存放数据
		redisTemplate.opsForValue().set(key, JSON.toJSONString(user));

		//第二部分：返回map数据，包括token的值，并且经过jwt加密的数据
		Map<String,Object> map = new HashMap();
		map.put(TokenConstants.USER_KEY,token);
		Map<String,Object> resultMap = new HashMap();
		resultMap.put("access_token", JwtUtil.createToken(map));
		return resultMap;
	}
	//2. 生成redis的key
	private String getKey(String token) {
		return TokenConstants.LOGIN_USER_REDIS_KEY + token;
	}

	//2. 根据用户名查询用户
	private LoginUser findByUserByUsername(String username) {
		User user = this.getOne(new QueryWrapper<User>().eq("id", username));
		LoginUser loginUser = new LoginUser();
		loginUser.setUser(user);
		return loginUser;
	}

	@Test
	public void test01(){
		String access_token = "eyJhbGciOiJIUzI1NiJ9.eyJ1c2VyX2tleSI6IjEyOTNkMmVmMzNjYjRhYjA5NGRjYWJmMTJkZTNiMmU1In0.lwV8viG0R3_2ki0bAS5YP4Pq9yvEQVIiVJvTZ1WSrBg";
		Claims claims = JwtUtil.parseToken(access_token);
		Object token = claims.get("user_key");
		System.out.println("token = " + token);  // 1293d2ef33cb4ab094dcabf12de3b2e5
	}
}
